﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace Moonlite.UI.Shell.Controls {
    public partial class ListBoxEx : ListBox {
        private ImageList imageList = new ImageList();
        public ImageList ImageList {
            get { return imageList; }
            set {
                imageList = value;
                if (imageList != null) {
                    ItemHeight = imageList.ImageSize.Height;
                }
            }
        }
        protected override void OnDrawItem(DrawItemEventArgs e) {
            e.DrawBackground();
            e.DrawFocusRectangle();
            ListBoxItemEx item;
            Rectangle bounds = e.Bounds;
            Size imageSize = imageList.ImageSize;
            if (Items.Count > 0) {
                try {
                    item = (ListBoxItemEx)Items[e.Index];
                    if (item.ImageIndex != -1) {
                        imageList.Draw(e.Graphics, bounds.Left, bounds.Top, item.ImageIndex);
                        e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor), bounds.Left + imageSize.Width, bounds.Top);
                    }
                    else {
                        e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor), bounds.Left, bounds.Top);
                    }
                }
                catch {
                    if (e.Index != -1) {
                        e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), bounds.Left, bounds.Top);
                    }
                    else {
                        e.Graphics.DrawString(Text, e.Font, new SolidBrush(e.ForeColor), bounds.Left, bounds.Top);
                    }
                }
            }
            base.OnDrawItem(e);
        }
        public ListBoxEx() {
            InitializeComponent();
            DrawMode = DrawMode.OwnerDrawFixed;
        }
    }
}
